package java_thinking.unit_11._11_13;

import java.util.Iterator;

/**
 * @Description :
 * @author: cww
 * @DateTime: 2019/3/19 8:44
 */

public class IterableClass implements Iterable<String> {

    public String[] words = ("And that is how we know the Earth to be banana-shaped.").split(" ");
    /**
     * iterator()方法返回的是实现了Iterator<String>的匿名内部类的实例，该匿名内部类可以遍历数组中所有单词
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int i = 0;

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove");
            }

            @Override
            public boolean hasNext() {
                return i<words.length;
            }

            @Override
            public String next() {
                return words[i++];
            }
        };
    }

    public static void main(String[] args) {
        //for原理就是执行Iterator中的hasNext，如果true就next()取的当前元素，以此循环在序列中移动
        for (Object s :new IterableClass()){
            System.out.print(s+" ");
        }
    }
}
